# Makefile for Protocol Manager Application

# 编译器设置
CC = gcc
CFLAGS = -Wall -Wextra -std=c99 -O2 -g
LDFLAGS = 

# 目录设置
SRC_DIR = src
INCLUDE_DIR = include
BUILD_DIR = ../../build/manager
OBJ_DIR = $(BUILD_DIR)/obj
BIN_DIR = $(BUILD_DIR)/bin

# 包含路径
INCLUDES = -I$(INCLUDE_DIR) \
           -I../../common/logs/include \
           -I../../common/config/include

# 源文件和目标文件
SOURCES = $(wildcard $(SRC_DIR)/*.c)
OBJECTS = $(SOURCES:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o)

# 可执行文件
TARGET = $(BIN_DIR)/protocol_manager

# 依赖对象文件 - common模块的对象文件
COMMON_LOGS_OBJ = ../../build/common/logs/src/logger.o
COMMON_CONFIG_OBJ = ../../build/common/config/src/cfg_utils.o
COMMON_OBJECTS = $(COMMON_LOGS_OBJ) $(COMMON_CONFIG_OBJ)

# 默认目标
all: build_common directories $(TARGET)

# 构建common模块
build_common:
	@echo "构建common模块..."
	@$(MAKE) -C ../../common check_compile >/dev/null 2>&1 || true

# 创建目录
directories:
	@mkdir -p $(OBJ_DIR)
	@mkdir -p $(BIN_DIR)

# 编译目标文件
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c
	@echo "编译: $<"
	$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

# 链接可执行文件
$(TARGET): $(OBJECTS)
	@echo "链接: $@"
	@if [ ! -f "$(COMMON_LOGS_OBJ)" ] || [ ! -f "$(COMMON_CONFIG_OBJ)" ]; then \
		echo "错误: common模块对象文件不存在"; \
		echo "请先运行: make -C ../../common"; \
		exit 1; \
	fi
	$(CC) $(LDFLAGS) -o $@ $(OBJECTS) $(COMMON_OBJECTS) -pthread

# 清理
clean:
	@echo "清理构建文件..."
	rm -rf $(BUILD_DIR)

# 运行
run: $(TARGET)
	@echo "运行协议管理器..."
	$(TARGET) -c config/manager.conf

# 帮助信息
help:
	@echo "协议管理器构建系统"
	@echo "============================"
	@echo "可用目标:"
	@echo "  all      - 构建应用（默认）"
	@echo "  clean    - 清理构建文件"
	@echo "  run      - 运行应用"
	@echo "  help     - 显示此帮助信息"

.PHONY: all build_common directories clean run help

